package com.example.teacher.Service.Impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.constants.RdsConstants;
import com.example.common.domain.pojo.HomeworkQuestion;
import com.example.common.domain.pojo.Question;
import com.example.common.domain.vo.QuestionVo;
import com.example.common.utils.CacheClient;
import com.example.teacher.Service.HomeworkQuestionService;
import com.example.teacher.Service.HomeworkService;
import com.example.teacher.Service.QuestionService;
import com.example.teacher.domain.dto.QuestionDto;
import com.example.teacher.mapper.QuestionMapper;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private HomeworkService homeworkService;
    @Autowired
    private HomeworkQuestionService homeworkQuestionService;
    @Autowired
    private CacheClient cacheClient;

    @Override
    public Page<QuestionVo> queryQuestionPage(QuestionDto dto, Integer pageNum, Integer pageSize) {
        // 1. 构建分页对象
        Page<Question> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();

        // 难度级别过滤
        if (dto.getDifficulty() != null) {
            queryWrapper.eq(Question::getDifficulty, dto.getDifficulty());
        }
        // 课程ID过滤
        if (StringUtils.hasText(dto.getCourseId())) {
            queryWrapper.eq(Question::getCourseId, dto.getCourseId());
        }
        // 题目名称模糊查询
        if (StringUtils.hasText(dto.getQuestionText())) {
            queryWrapper.like(Question::getQuestionText, dto.getQuestionText());
        }
        // 题目类型过滤
        if (dto.getType() != null) {
            queryWrapper.eq(Question::getType, dto.getType());
        }
        // 假设使用 MySQL 的 JSON_CONTAINS 函数   知识点过滤
        if (dto.getKnowledgePointId() != null) {
            queryWrapper.apply("JSON_CONTAINS(knowledge_points, '\"" + dto.getKnowledgePointId() + "\"')");
        }
        // 开始时间范围过滤
        if (dto.getCreatedAt() != null) {
            queryWrapper.ge(Question::getCreatedAt, dto.getCreatedAt());    //大于
        }

        // 结束时间范围过滤
        if (dto.getUpdatedAt() != null) {
            queryWrapper.le(Question::getUpdatedAt, dto.getUpdatedAt());  //小于
        }
        Page<Question> questionPage = questionMapper.selectPage(page, queryWrapper.orderByDesc(Question::getUpdatedAt));
        // 转换为 DTO 分页
        Page<QuestionVo> dtoPage = new Page<>();
        dtoPage.setCurrent(questionPage.getCurrent());
        dtoPage.setSize(questionPage.getSize());
        dtoPage.setTotal(questionPage.getTotal());
        dtoPage.setPages(questionPage.getPages());
        dtoPage.setRecords(
                questionPage.getRecords().stream()
                        .map(QuestionVo::from)
                        .collect(Collectors.toList())
        );

        // 3. 执行分页查询（按更新时间倒序排列）
        return dtoPage;
    }

    @Override
    public Page<QuestionVo> selectQuestionPage(String homeworkId, Integer pageNum, Integer pageSize) {
        List<HomeworkQuestion> homeworkQuestions = homeworkQuestionService.getByHomeworkId(homeworkId);

        // 提取题目ID列表
        List<String> questionIds = homeworkQuestions.stream()
                .map(HomeworkQuestion::getQuestionId)
                .collect(Collectors.toList());

        // 构建分页对象
        Page<Question> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        if (!questionIds.isEmpty()) {
            queryWrapper.in(Question::getId, questionIds);
        } else {
            queryWrapper.eq(Question::getId, "");
        }

        // 查询数据库
        Page<Question> questionPage = questionMapper.selectPage(page, queryWrapper.orderByDesc(Question::getUpdatedAt));

        // 转换为 DTO 分页
        Page<QuestionVo> dtoPage = new Page<>();
        dtoPage.setCurrent(questionPage.getCurrent());
        dtoPage.setSize(questionPage.getSize());
        dtoPage.setTotal(questionPage.getTotal());
        dtoPage.setPages(questionPage.getPages());
        dtoPage.setRecords(
                questionPage.getRecords().stream()
                        .map(QuestionVo::from)
                        .collect(Collectors.toList())
        );

        return dtoPage;
    }

    @Override
    public void saveQuestion(Question question) {

        super.save(question);
    }

    @Override
    public void MoreSaveQuestion(List<Question> questions) {
        super.saveBatch(questions);
    }

    @Override
    public QuestionVo getQuestionById(String id) {
        Question question = cacheClient.queryWithLogicalExpire(
                RdsConstants.QUESTION_INFO,
                id,
                Question.class,
                this::getById, // 使用MyBatis-Plus的基础方法
                RdsConstants.CACHE_NULL_TTL,
                TimeUnit.MINUTES,
                false
        );
        QuestionVo questionVo = QuestionVo.from(question);
        return questionVo;
    }

    @Override
    public void updateQuestion(Question question) {
        // 参数校验：确保主键存在
        if (question.getId() == null) {
            log.warn("更新题目时必须提供id");
            throw new IllegalArgumentException("更新题目时必须提供id");
        }
        // 构建UpdateWrapper
        UpdateWrapper<Question> updateWrapper = new UpdateWrapper<>();
        // 设置更新条件（主键）
        updateWrapper.lambda()
                .eq(Question::getId, question.getId());
        // 动态设置需要更新的字段（只更新非null值）
        LambdaUpdateWrapper<Question> lambdaUpdate = updateWrapper.lambda();

        // 基础字段更新
        if (question.getQuestionText() != null) {
            lambdaUpdate.set(Question::getQuestionText, question.getQuestionText());
        }
        if (question.getCourseId() != null) {
            lambdaUpdate.set(Question::getCourseId, question.getCourseId());
        }
        // 枚举类型更新
        if (question.getType() != null) {
            lambdaUpdate.set(Question::getType, question.getType());
        }
        if (question.getDifficulty() != null) {
            lambdaUpdate.set(Question::getDifficulty, question.getDifficulty());
        }
        // JSON字段更新（Map和List）
        if (question.getOptions() != null && !question.getOptions().isEmpty()) {
            lambdaUpdate.set(Question::getOptions, question.getOptions());
        }
        if (question.getCorrectAnswers() != null && !question.getCorrectAnswers().isEmpty()) {
            lambdaUpdate.set(Question::getCorrectAnswers, question.getCorrectAnswers());
        }
        // 其他字段更新
        if (question.getExplanation() != null) {
            lambdaUpdate.set(Question::getExplanation, question.getExplanation());
        }
        if (question.getScore() != null) {
            lambdaUpdate.set(Question::getScore, question.getScore());
        }
        if (question.getRemarks() != null) {
            lambdaUpdate.set(Question::getRemarks, question.getRemarks());
        }
        if (question.getMediaUrl() != null) {
            lambdaUpdate.set(Question::getMediaUrl, question.getMediaUrl());
        }
        // 自动填充更新时间（若实体类未通过注解自动处理）
        lambdaUpdate.set(Question::getUpdatedAt, new Timestamp(System.currentTimeMillis()));
        // 执行更新操作
        int rows = questionMapper.update(null, updateWrapper);
        // 检查更新结果
        if (rows == 0) {
            log.warn("更新题目失败，未找到记录，id={}");
            throw new EntityNotFoundException("未找到对应题目记录，id=" + question.getId());
        }
    }
}
